package com.ctyun.xstore.s3.controller;

import com.ctyun.xstore.s3.api.object.DownloadObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class FileController {

    /**
     * @param fileName   文件名称
     * @param fileBlocks 文件块名称，多个文件块用;连接
     * @param response
     * @return
     */
    @RequestMapping("download")
    public String downloadFile(@RequestParam(value = "file", required = true) String fileName, String fileBlocks, HttpServletResponse response) {
        String bucketName = "vod-origin-60904cdc-c9fe-4a64-9386-7803f9bff21f";
        BufferedOutputStream bos = null;
        try {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            bos = new BufferedOutputStream(response.getOutputStream());
            if (fileBlocks != null) {
                for (String blockName : fileBlocks.split(";")) {
                    if(!DownloadObject.downObject2OutputStream(bucketName, blockName, bos)){
                        return "error";
                    }
                }
            } else {
                if(DownloadObject.downObject2OutputStream(bucketName, fileName, bos)){
                    return "error";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
